// composables/usePagination.js
import { ref, reactive } from 'vue'
import Request from '@/commons/request'
import Message from '@/components/message'
import storage from '@/commons/storage'

/**
 * 分页功能 composable
 * @param {Object} urlConfig - URL 配置对象
 * @returns {Object} 包含分页相关状态和方法的对象
 */
export function usePagination(urlConfig = {}) {
  // 响应式数据
  const queryParam = reactive({})
  const desserts = ref([])
  const loading = ref(false)
  const selectedRowKeys = ref([])
  const selectionRows = ref([])
  const superQueryParams = ref('')
  const page = reactive({
    pageno: 1,
    limit: 10
  })
  const pageData = ref({})
  const user = ref({})
  const overlay = ref(false)

  // URL 配置
  const url = reactive(urlConfig)

  /**
   * 加载数据
   */
  const loadData = () => {
    if (!url.list) {
      Message.toast('请先设置url.list属性', { color: 'warning' })
      return
    }
    
    const params = getQueryParams()
    loading.value = true
    
    Request.postJson(url.list, params)
      .then((res) => {
        if (res.meta.success || res.data) {
          desserts.value = res.data?.rows || []
          pageData.value = res.data
        }
        loading.value = false
      })
      .catch((error) => {
        console.error('加载数据失败:', error)
        loading.value = false
      })
  }

  /**
   * 获取查询参数
   * @returns {Object} 查询参数对象
   */
  const getQueryParams = () => {
    // 确保用户信息已加载
    if (!user.value.areacode && !queryParam.areaCode) {
      user.value = storage.get('user') || {}
    }
    
    if (!queryParam.areaCode) {
      queryParam.areaCode = user.value?.areacode
    }
    
    const codex = Object.assign({}, queryParam)
    const params = {
      pageno: page.pageno,
      limit: page.limit,
      codex: codex
    }
    return params
  }

  /**
   * 搜索查询
   */
  const searchQuery = () => {
    page.pageno = 1
    page.limit = 10
    loadData()
  }

  /**
   * 清除选中项
   */
  const clearSelected = () => {
    selectedRowKeys.value = []
    selectionRows.value = []
  }

  /**
   * 分页变化处理
   * @param {Object} pageInfo - 分页信息
   */
  const getListPage = (pageInfo) => {
    page.pageno = pageInfo.pageno
    page.limit = pageInfo.limit
    loadData()
  }

  /**
   * 树形选择处理
   * @param {string} areaCode - 区域代码
   */
  const selectTree = (areaCode) => {
    queryParam.areaCode = areaCode
    loadData()
  }

  /**
   * 批量删除
   */
  const batchDelete = () => {
    if (!url.delete) {
      Message.toast('请设置url.delete属性!', { color: 'warning' })
      return
    }
    
    if (selectedRowKeys.value.length <= 0) {
      Message.toast('请选择一条记录!', { color: 'warning' })
      return
    }
    
    const ids = selectedRowKeys.value.map(item => item.id).join(',')
    
    Message.confirm(
      { title: '确认删除', text: '是否删除选中数据?' },
      (result) => {
        if (result) {
          Request.getForm(url.delete, { id: ids })
            .then((res) => {
              if (res.meta.success) {
                Message.toast('删除成功', { color: 'success' })
                loadData()
                clearSelected()
              } else {
                Message.toast('删除失败', { color: 'warning' })
              }
            })
            .catch((error) => {
              console.error('批量删除失败:', error)
              Message.toast('删除失败', { color: 'warning' })
            })
        }
      }
    )
  }

  /**
   * 删除单条记录
   * @param {string|number} id - 要删除的记录ID
   * @param {string} text - 确认提示文本
   */
  const deleteItem = (id, text) => {
    if (!url.delete) {
      // 兼容处理 vtk 对象
      if (window.$vtk?.message?.toast) {
        window.$vtk.message.toast('请设置url.delete属性!', { color: 'warning' })
      } else {
        Message.toast('请设置url.delete属性!', { color: 'warning' })
      }
      return
    }
    
    // 兼容处理 vtk 对象
    const confirmMethod = window.$vtk?.message?.confirm || Message.confirm
    const toastMethod = window.$vtk?.message?.toast || Message.toast
    
    confirmMethod(
      { title: '确认删除', text: text || '是否删除?' },
      (result) => {
        if (result) {
          Request.getForm(url.delete, { id: id })
            .then((res) => {
              if (res.meta.success) {
                toastMethod('删除成功', { color: 'success' })
                loadData()
              } else {
                toastMethod('删除失败', { color: 'warning' })
              }
            })
            .catch((error) => {
              console.error('删除失败:', error)
              toastMethod('删除失败', { color: 'warning' })
            })
        }
      }
    )
  }

  /**
   * 复制记录
   * @param {string|number} id - 要复制的记录ID
   * @param {string} text - 确认提示文本
   */
  const copyItem = (id, text) => {
    if (!url.copy) {
      Message.toast('请设置url.copy!', { color: 'warning' })
      return
    }
    
    Message.confirm(
      { title: '拷贝', text: text || '是否确认拷贝当前数据?' },
      (result) => {
        if (result) {
          Request.getForm(url.copy, { id: id })
            .then((res) => {
              if (res.meta.success) {
                Message.toast('拷贝成功', { color: 'success' })
                loadData()
              } else {
                Message.toast('拷贝失败', { color: 'warning' })
              }
            })
            .catch((error) => {
              console.error('拷贝失败:', error)
              Message.toast('拷贝失败', { color: 'warning' })
            })
        }
      }
    )
  }

  /**
   * 导出数据
   */
  const exportData = () => {
    if (!url.exp) {
      Message.toast('请设置url.exp属性!', { color: 'warning' })
      return
    }
    
    overlay.value = true
    const params = getQueryParams()
    
    Request.exp(url.exp, params)
      .then((res) => {
        if (res) {
          const disposition = res.headers['content-disposition']
          const filename = decodeURI(
            disposition.substring(
              disposition.indexOf('filename=') + 9,
              disposition.length
            )
          )
          
          const blob = new Blob([res.data], {
            type: 'application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
          })
          
          if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob)
          } else {
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = URL.createObjectURL(blob)
            link.download = filename
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          }
        }
        overlay.value = false
      })
      .catch((error) => {
        console.error('导出数据失败:', error)
        overlay.value = false
      })
  }

  /**
   * 更新 URL 配置
   * @param {Object} newUrlConfig - 新的 URL 配置
   */
  const updateUrlConfig = (newUrlConfig) => {
    Object.assign(url, newUrlConfig)
  }

  /**
   * 重置查询参数
   */
  const resetQueryParams = () => {
    Object.keys(queryParam).forEach(key => {
      delete queryParam[key]
    })
  }

  /**
   * 重置分页
   */
  const resetPage = () => {
    page.pageno = 1
    page.limit = 10
  }

  /**
   * 初始化用户信息
   */
  const initUser = () => {
    user.value = storage.get('user') || {}
  }

  return {
    // 响应式数据
    queryParam,
    desserts,
    loading,
    selectedRowKeys,
    selectionRows,
    superQueryParams,
    page,
    pageData,
    user,
    overlay,
    url,

    // 方法
    loadData,
    getQueryParams,
    searchQuery,
    clearSelected,
    getListPage,
    selectTree,
    batchDelete,
    deleteItem,
    copyItem,
    exportData,
    updateUrlConfig,
    resetQueryParams,
    resetPage,
    initUser
  }
}

// 保持向后兼容的默认导出
export default usePagination